using Microsoft.Extensions.Logging;
using System.Collections.Concurrent;

namespace AndroidApp2
{
    /// <summary>
    /// 日志级别枚举
    /// </summary>
    public enum LogLevel
    {
        Debug = 0,
        Info = 1,
        Warning = 2,
        Error = 3
    }
    
    /// <summary>
    /// 日志消息事件参数
    /// </summary>
    public class LogMessageEventArgs : EventArgs
    {
        public string Message { get; }
        public DateTime Timestamp { get; }
        public string Source { get; }
        public LogLevel Level { get; }
        
        public LogMessageEventArgs(string message, string source, LogLevel level = LogLevel.Info)
        {
            Message = message;
            Source = source;
            Level = level;
            Timestamp = DateTime.Now;
        }
    }
    
    /// <summary>
    /// 日志管理器 - 基于Microsoft.Extensions.Logging
    /// 提供结构化日志、高性能和完整的日志功能
    /// </summary>
    public class LogManager : IDisposable
    {
        /// <summary>
        /// 日志工厂
        /// </summary>
        private readonly ILoggerFactory _loggerFactory;
        
        /// <summary>
        /// 主日志记录器
        /// </summary>
        private readonly ILogger<LogManager> _logger;
        
        /// <summary>
        /// 日志缓存队列（线程安全）
        /// </summary>
        private readonly ConcurrentQueue<LogMessageEventArgs> _logCache = new();
        
        /// <summary>
        /// 最大缓存大小
        /// </summary>
        private const int MaxCacheSize = 1000;
        
        /// <summary>
        /// 当前缓存大小
        /// </summary>
        private int _cacheSize = 0;
        
        /// <summary>
        /// 最小日志级别
        /// </summary>
        private LogLevel _minLogLevel = LogLevel.Debug;
        
        /// <summary>
        /// 日志消息事件
        /// </summary>
        public event EventHandler<LogMessageEventArgs>? LogMessageReceived;
        
        /// <summary>
        /// 单例实例
        /// </summary>
        private static LogManager? _instance;
        
        /// <summary>
        /// 线程锁
        /// </summary>
        private static readonly object _lock = new object();
        
        /// <summary>
        /// 私有构造函数
        /// </summary>
        private LogManager()
        {
            _loggerFactory = LoggerFactory.Create(builder =>
            {
                builder
                    .AddConsole()
                    .AddDebug()
                    .SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Debug);
            });
            
            _logger = _loggerFactory.CreateLogger<LogManager>();
        }
        
        /// <summary>
        /// 获取单例实例
        /// </summary>
        public static LogManager Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_lock)
                    {
                        if (_instance == null)
                        {
                            _instance = new LogManager();
                        }
                    }
                }
                return _instance;
            }
        }
        
        /// <summary>
        /// 设置最小日志级别
        /// </summary>
        /// <param name="level">最小日志级别</param>
        public void SetMinLogLevel(LogLevel level)
        {
            lock (_lock)
            {
                _minLogLevel = level;
            }
        }
        
        /// <summary>
        /// 获取日志缓存
        /// </summary>
        /// <returns>日志缓存副本</returns>
        public List<LogMessageEventArgs> GetLogCache()
        {
            return _logCache.ToList();
        }
        
        /// <summary>
        /// 清除日志缓存
        /// </summary>
        public void ClearLogCache()
        {
            while (_logCache.TryDequeue(out _))
            {
                Interlocked.Decrement(ref _cacheSize);
            }
        }
        
        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="message">日志消息</param>
        /// <param name="source">日志来源</param>
        /// <param name="level">日志级别</param>
        public void Log(string message, string source = "系统", LogLevel level = LogLevel.Info)
        {
            // 检查日志级别
            if (level < _minLogLevel)
                return;
            
            // 使用Microsoft.Extensions.Logging记录
            var msLevel = ConvertToMSLogLevel(level);
            using var scope = _logger.BeginScope(source);
            _logger.Log(msLevel, message);
            
            // 格式化消息
            var timestamp = DateTime.Now.ToString("HH:mm:ss.fff");
            var levelStr = level.ToString().ToUpper();
            var formattedMessage = level >= LogLevel.Warning 
                ? $"[{timestamp}] [{levelStr}] [{source}] {message}"
                : $"[{timestamp}] [{source}] {message}";
            
            var logEvent = new LogMessageEventArgs(formattedMessage, source, level);
            
            // 添加到缓存
            AddToCache(logEvent);
            
            // 触发事件
            LogMessageReceived?.Invoke(this, logEvent);
        }
        
        /// <summary>
        /// 记录活动日志
        /// </summary>
        /// <param name="message">日志消息</param>
        public void LogActivity(string message)
        {
            Log(message, "活动", LogLevel.Info);
        }
        
        /// <summary>
        /// 记录服务日志
        /// </summary>
        /// <param name="message">日志消息</param>
        public void LogService(string message)
        {
            Log(message, "服务", LogLevel.Info);
        }
        
        /// <summary>
        /// 记录Socket日志
        /// </summary>
        /// <param name="message">日志消息</param>
        public void LogSocket(string message)
        {
            Log(message, "Socket", LogLevel.Info);
        }
        
        /// <summary>
        /// 记录错误日志
        /// </summary>
        /// <param name="message">错误消息</param>
        /// <param name="source">错误来源</param>
        public void LogError(string message, string source = "错误")
        {
            Log(message, source, LogLevel.Error);
        }
        
        /// <summary>
        /// 记录错误日志（带异常）
        /// </summary>
        /// <param name="message">错误消息</param>
        /// <param name="exception">异常对象</param>
        /// <param name="source">错误来源</param>
        public void LogError(string message, Exception exception, string source = "错误")
        {
            using var scope = _logger.BeginScope(source);
            _logger.LogError(exception, message);
            
            var fullMessage = $"{message}: {exception.Message}";
            var timestamp = DateTime.Now.ToString("HH:mm:ss.fff");
            var formattedMessage = $"[{timestamp}] [ERROR] [{source}] {fullMessage}";
            
            var logEvent = new LogMessageEventArgs(formattedMessage, source, LogLevel.Error);
            AddToCache(logEvent);
            LogMessageReceived?.Invoke(this, logEvent);
        }
        
        /// <summary>
        /// 记录警告日志
        /// </summary>
        /// <param name="message">警告消息</param>
        /// <param name="source">警告来源</param>
        public void LogWarning(string message, string source = "警告")
        {
            Log(message, source, LogLevel.Warning);
        }
        
        /// <summary>
        /// 记录信息日志
        /// </summary>
        /// <param name="message">信息消息</param>
        /// <param name="source">信息来源</param>
        public void LogInfo(string message, string source = "信息")
        {
            Log(message, source, LogLevel.Info);
        }
        
        /// <summary>
        /// 记录调试日志
        /// </summary>
        /// <param name="message">调试消息</param>
        /// <param name="source">调试来源</param>
        public void LogDebug(string message, string source = "调试")
        {
            Log(message, source, LogLevel.Debug);
        }
        
        /// <summary>
        /// 添加到缓存
        /// </summary>
        /// <param name="logEvent">日志事件</param>
        private void AddToCache(LogMessageEventArgs logEvent)
        {
            _logCache.Enqueue(logEvent);
            Interlocked.Increment(ref _cacheSize);
            
            // 清理超出限制的缓存
            while (_cacheSize > MaxCacheSize)
            {
                if (_logCache.TryDequeue(out _))
                {
                    Interlocked.Decrement(ref _cacheSize);
                }
                else
                {
                    break;
                }
            }
        }
        
        /// <summary>
        /// 转换到Microsoft.Extensions.Logging日志级别
        /// </summary>
        /// <param name="level">自定义日志级别</param>
        /// <returns>Microsoft日志级别</returns>
        private static Microsoft.Extensions.Logging.LogLevel ConvertToMSLogLevel(LogLevel level)
        {
            return level switch
            {
                LogLevel.Debug => Microsoft.Extensions.Logging.LogLevel.Debug,
                LogLevel.Info => Microsoft.Extensions.Logging.LogLevel.Information,
                LogLevel.Warning => Microsoft.Extensions.Logging.LogLevel.Warning,
                LogLevel.Error => Microsoft.Extensions.Logging.LogLevel.Error,
                _ => Microsoft.Extensions.Logging.LogLevel.Information
            };
        }
        
        /// <summary>
        /// 清除所有事件订阅
        /// </summary>
        public void ClearSubscriptions()
        {
            LogMessageReceived = null;
        }
        
        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            _loggerFactory?.Dispose();
        }
    }
}